package com.by.hellosecurityoauth2.controller;

import com.by.hellosecurityoauth2.domain.TAuthority;
import com.by.hellosecurityoauth2.service.AuthorityService;
import com.by.hellosecurityoauth2.controller.request.AuthorityRequestBean;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 白羽
 * @Date 2022-12-13 09:15:55
 */
@Api(tags = "权限管理")
@RestController
@RequestMapping("/authority")
public class AuthorityController {
    /**
     * 服务对象
     */
    private AuthorityService authorityService;

    public AuthorityController(AuthorityService authorityService) {
        this.authorityService = authorityService;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @Operation(summary = "根据id获取权限信息")
    @PreAuthorize("hasAuthority('user:authority:get')")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public TAuthority getAuthorityById(@PathVariable("id") Long id) {
        return authorityService.findById(id);
    }

    @Operation(summary = "根据关键字查询权限列表")
    @PreAuthorize("hasAuthority('user:authority:get')")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public Page<TAuthority> list(@RequestParam @Parameter(description = "页数，从1开始", required = true) int page,
                                 @RequestParam @Parameter(description = "每页的条数", required = true) int limit,
                                 HttpServletRequest request) {

        return authorityService.list(page - 1, limit);

    }

    @Operation(summary = "创建权限信息")
    @PreAuthorize("hasAuthority('user:authority:create')")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public TAuthority createAuthority(@RequestBody AuthorityRequestBean bean, HttpServletRequest request) {
        return authorityService.create(bean);
    }

    @Operation(summary = "根据id修改权限信息")
    @PreAuthorize("hasAuthority('user:authority:update')")
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public TAuthority updateAuthorityById(@PathVariable("id") Long id, @RequestBody AuthorityRequestBean bean, HttpServletRequest request) {
        return authorityService.updateById(id, bean);
    }

    @Operation(summary = "根据id删除权限信息")
    @PreAuthorize("hasAuthority('user:authority:delete')")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteAuthorityById(@PathVariable("id") Long id, HttpServletRequest request) {
        authorityService.deleteById(id);
    }

}